package cn.tedu.aiumall.passport.security;

import cn.tedu.aiumall.passport.mapper.AdminMapper;
import cn.tedu.aiumall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.info("Spring Security自动调用loadUserByUsername()方法获取用户名为【{}】的用户详情……",s);
         AdminLoginInfoVO loginAdminByUsername = adminMapper.getLoginInfoByUsername(s);
         if (loginAdminByUsername==null){
             String message = "登录失败，用户名不存在！";
             log.warn(message);
             throw new BadCredentialsException(message);
            }

        List<String> permissions = loginAdminByUsername.getPermissions();
         List<GrantedAuthority> authorities=new ArrayList<>();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        AdminDetails adminDetails=new AdminDetails(
                loginAdminByUsername.getUsername(),
                loginAdminByUsername.getPassword(),
                loginAdminByUsername.getEnable()==1,
                authorities
         );
        adminDetails.setId(loginAdminByUsername.getId());
         /*UserDetails userDetails= User.builder()
                 .username(loginAdmin.getUsername())
                 .password(loginAdmin.getPassword())
                 .accountLocked(false)
                 .disabled(loginAdmin.getEnable()==0)
                 .accountExpired(false)
                 .credentialsExpired(false)
                 .authorities(loginAdmin.getPermissions().toArray(new String[] {}))
                 .build();*/
        log.info("向Spring Security框架返回UserDetails对象:{}",adminDetails);
        return adminDetails;
    }

}
